import React, {useEffect, useState} from 'react';
import {Box, Typography, Tooltip, Paper, CircularProgress} from '@mui/material';
import {getArchiveList, ArchiveData} from '@services/front/archive';
import {useTheme} from "@mui/material/styles";

// 工具函数：将归档数据按年份分组
function groupByYear(archives: ArchiveData[]) {
    const map: Record<string, ArchiveData[]> = {};
    archives.forEach(item => {
        const year = item.month.split('-')[0];
        if (!map[year]) map[year] = [];
        map[year].push(item);
    });
    return map;
}

const ArchiveList: React.FC = () => {
    const theme = useTheme();
    const [archives, setArchives] = useState<ArchiveData[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState('');

    useEffect(() => {
        async function fetchData() {
            setLoading(true);
            try {
                const data = await getArchiveList({});
                setArchives(data || []);
            } catch (e: any) {
                setError(e.message || '加载失败');
            } finally {
                setLoading(false);
            }
        }

        fetchData();
    }, []);

    const grouped = groupByYear(archives);
    const years = Object.keys(grouped).sort((a, b) => b.localeCompare(a));

    return (
        <Box sx={{
            justifyContent: 'center', alignItems: 'center', minHeight: '80vh',
            bgcolor: theme.palette.background.default,
            color: theme.palette.text.primary,
            display: 'grid',
            gridTemplateColumns: {xs: 'repeat(1, minmax(0, 1fr))', md: 'repeat(2, minmax(0, 1fr))'},
            transition: 'background 0.3s, color 0.3s',
            px: {xs: 1, md: 8},
            py: 6,
        }}>
            <Box sx={{position: 'relative', width: {xs: '100%', md: 900}, minHeight: 1000}}>
                {/* 竖直时间轴线和箭头 */}
                <Box
                    sx={{
                        position: 'absolute',
                        left: '50%',
                        top: 0,
                        bottom: 0,
                        width: '4px',
                        bgcolor: 'primary.main',
                        transform: 'translateX(-50%)',
                        zIndex: 1,
                    }}
                />
                {/* 箭头 */}
                <Box
                    sx={{
                        position: 'absolute',
                        left: '50%',
                        top: -18,
                        width: 0,
                        height: 0,
                        borderLeft: '12px solid transparent',
                        borderRight: '12px solid transparent',
                        borderBottom: '18px solid',
                        borderBottomColor: 'primary.main',
                        transform: 'translateX(-50%)',
                        zIndex: 2,
                    }}
                />
                {/* 内容 */}
                {loading ? (
                    <Box sx={{display: 'flex', justifyContent: 'center', mt: 10}}>
                        <CircularProgress/>
                    </Box>
                ) : error ? (
                    <Typography color="error" align="center">{error}</Typography>
                ) : (
                    years.map((year, i) => (
                        <Box key={year} sx={{mt: i === 0 ? 4 : 8}}>
                            <Typography variant="h5" align="left" color="primary"
                                        sx={{mb: 3, fontWeight: 600}}>{year}年</Typography>
                            {grouped[year].map((item, idx) => {
                                const isLeft = (idx % 2 === 0);
                                return (
                                    <Box key={item.month} sx={{
                                        display: 'flex',
                                        flexDirection: isLeft ? 'row' : 'row-reverse',
                                        alignItems: 'center',
                                        ml: isLeft ? '18.9%' : -1,
                                        mr: isLeft ? -1 : '18.9%',
                                    }}>
                                        <Tooltip
                                            title={
                                                <Box>
                                                    {(item.articles && Array.isArray(item.articles) && item.articles.length > 0) ? (
                                                        item.articles.map((art: any) => (
                                                            <Paper key={art.id} sx={{
                                                                display: 'flex',
                                                                alignItems: 'center',
                                                                mb: 1,
                                                                p: 1
                                                            }} variant="outlined">
                                                                {art.titleImage && (
                                                                    <Box component="img" src={art.titleImage}
                                                                         alt={art.title} sx={{
                                                                        width: 48,
                                                                        height: 48,
                                                                        mr: 1,
                                                                        borderRadius: 1,
                                                                        objectFit: 'cover'
                                                                    }}/>
                                                                )}
                                                                <Box sx={{flex: 1}}>
                                                                    <Typography variant="subtitle2"
                                                                                noWrap>{art.title}</Typography>
                                                                    <Typography variant="caption"
                                                                                color="text.secondary">{art.createData ? (new Date(art.createData)).toLocaleDateString() : ''}</Typography>
                                                                </Box>
                                                            </Paper>
                                                        ))
                                                    ) : (
                                                        <Typography variant="body2"
                                                                    color="text.secondary">暂无文章</Typography>
                                                    )}
                                                </Box>
                                            }
                                            arrow
                                            placement={isLeft ? 'right' : 'left'}
                                            componentsProps={{
                                                tooltip: {
                                                    sx: {
                                                        bgcolor: theme.palette.background.paper,
                                                        color: theme.palette.text.primary,
                                                        boxShadow: 5,
                                                        borderRadius: 2,
                                                        p: 2,
                                                        minWidth: 260,
                                                        maxWidth: 400,
                                                    }
                                                }
                                            }}
                                        >
                                            <Paper elevation={3} sx={{
                                                p: 3,
                                                minWidth: 200,
                                                textAlign: 'center',
                                                cursor: 'pointer',
                                                bgcolor: 'background.paper',
                                                fontWeight: 600,
                                            }}>
                                                <Typography variant="subtitle1">{item.month}</Typography>
                                                <Typography variant="caption"
                                                            color="text.secondary">{Array.isArray(item.articles) ? item.articles.length : 0} 篇</Typography>
                                            </Paper>
                                        </Tooltip>
                                        {/* 连接线点保持原位 */}
                                        <Box sx={{
                                            width: 0,
                                            height: 0,
                                            borderRadius: '50%',
                                            border: '8px solid',
                                            borderColor: 'primary.main',
                                            mx: 3,
                                            zIndex: 2,
                                        }}/>
                                    </Box>
                                );
                            })}
                        </Box>
                    ))
                )}
            </Box>
        </Box>
    );
};

export default ArchiveList;
